<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>学生名单</span>
        <el-input
          placeholder="搜索学生用户或姓名"
          v-model="searchQuery"
          clearable
          style="width: 200px;margin-right: 20px;"
        />
        <div class="extra">
          <el-button @click="clearForm" type="primary">添加学生</el-button>
          <el-button 
            :disabled="selectedStudents.length === 0" 
            @click="deleteSelectedStudents" 
            type="danger"
          >
            批量删除
          </el-button>
        </div>
      </div>
    </template>

    <!-- 添加学生弹窗 -->
    <el-dialog v-model="dialogVisible" :title="title" width="30%">
      <el-form :model="studentModel" :rules="rules" ref="formRef" label-width="100px" style="padding-right: 30px">
        <el-form-item label="学生用户" prop="username">
          <el-input v-model="studentModel.username" minlength="1" maxlength="10"></el-input>
        </el-form-item>
        <el-form-item label="学生姓名" prop="name">
          <el-input v-model="studentModel.name" minlength="2" maxlength="6"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="studentModel.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="studentModel.phone"></el-input>
        </el-form-item>
        <el-form-item label="学院" prop="college">
          <el-input v-model="studentModel.college"></el-input>
        </el-form-item>
        <el-form-item label="年级" prop="yearOfStudy">
          <el-input v-model="studentModel.yearOfStudy"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="title == '添加学生' ? addStudent() : editStudent()">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 列表 -->
    <el-table 
      :data="paginatedStudents" 
      style="width: 100%" 
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection"></el-table-column>
      <el-table-column label="序号" width="70" type="index"> </el-table-column>
      <el-table-column label="学生用户" prop="username"></el-table-column>
      <el-table-column label="姓名" prop="name"></el-table-column>
      <el-table-column label="学院" prop="college"></el-table-column>
      <el-table-column label="年级" prop="yearOfStudy"></el-table-column>
      <el-table-column label="邮箱" prop="email"></el-table-column>
      <el-table-column label="手机" prop="phone"></el-table-column>
      <el-table-column label="操作" width="150">
        <template #default="{ row }">
          <el-button :icon="Edit" circle plain type="primary" @click="showStudent(row)"></el-button>
          <el-button :icon="Delete" circle plain type="danger" @click="deleteStudent(row)"></el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据"/>
      </template>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      background
      :current-page="currentPage"
      :page-size="pageSize"
      @current-change="handlePageChange"
      :total="filteredStudents.length">
    </el-pagination>
  </el-card>
</template>

<script setup>
import { Edit, Delete } from '@element-plus/icons-vue';
import { ref, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  getStudentService,
  addStudentService,
  updateStudentService,
  deleteService,
} from '../../api/student';

const students = ref([]);
// 弹框标题
const title = ref('');
// 控制添加学生弹窗
const dialogVisible = ref(false);
// 学生表单模型
const studentModel = ref({
  username: '',
  name: '',
  email: '',
  phone: '',
  college: '',
  yearOfStudy: '',
  id: 0,
});
// 搜索关键词
const searchQuery = ref('');
// 表单校验引用
const formRef = ref(null);

// 添加学生表单校验规则
const rules = {
  username: [
    { required: true, message: '请输入学生用户名', trigger: 'blur' },
    { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入学生姓名', trigger: 'blur' },
    { min: 2, max: 6, message: '长度在 2 到 6 个字符', trigger: 'blur' }
  ],
};

// 显示学生列表信息
const studentList = async () => {
  let res = await getStudentService();
  students.value = res.data;
};

// 计算出匹配搜索条件的学生列表
const filteredStudents = computed(() => {
  if (!searchQuery.value) return students.value;
  return students.value.filter(student =>
    student.username.includes(searchQuery.value) ||
    student.name.includes(searchQuery.value)
  );
});

// 计算分页后的学生数据
const currentPage = ref(1);
const pageSize = ref(8); 

const paginatedStudents = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  return filteredStudents.value.slice(start, start + pageSize.value);
});

// 处理选择变化的方法
const selectedStudents = ref([]);

const handleSelectionChange = (selection) => {
  selectedStudents.value = selection;
};

// 批量删除选中的学生
const deleteSelectedStudents = async () => {
  if (selectedStudents.value.length === 0) {
    ElMessage.warning('请选择要删除的学生');
    return;
  }
  ElMessageBox.confirm('您确定要删除这些学生吗?', '注意', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
  .then(async () => {
    for (const student of selectedStudents.value) {
      await deleteService(student.id);
    }
    selectedStudents.value = []; // 清空选择
    studentList(); // 刷新学生列表
    ElMessage.success('删除成功');
  })
  .catch(() => {
    ElMessage.info('删除已取消');
  });
};

// 页码改变事件
const handlePageChange = (page) => {
  currentPage.value = page;
};

// 添加学生弹窗
const addStudent = async () => {
  formRef.value.validate(async valid => {
    if (valid) {
      let res = await addStudentService(studentModel.value);
      if (res) {
        ElMessage.success(res.message ? res.message : '添加成功');
        studentList();
        dialogVisible.value = false;
      } else {
        ElMessage.error(res.message ? res.message : '很可惜，添加失败了');
      }
    }
  });
};

// 清空表单数据
const clearForm = () => {
  studentModel.value = {
    username: '',
    name: '',
    email: '',
    phone: '',
    college: '',
    yearOfStudy: '',
    id: 0,
  };
  title.value = '添加学生';
  dialogVisible.value = true;
  formRef.value?.resetFields();
};

// 显示学生的信息到编辑弹窗
const showStudent = (row) => {
  title.value = '编辑学生';
  Object.assign(studentModel.value, row);
  dialogVisible.value = true;
};

// 编辑学生
const editStudent = async () => {
  let res = await updateStudentService(studentModel.value);
  if (res) {
    ElMessage.success(res.message ? res.message : '修改成功');
    studentList();
    dialogVisible.value = false;
  } else {
    ElMessage.error(res.message ? res.message : '很可惜，修改失败了');
  }
};

// 删除学生
const deleteStudent = async (row) => {
  ElMessageBox.confirm('您确定要删除这个学生吗?', '注意', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    let res = await deleteService(row.id);
    if (res) {
      ElMessage.success(res.message ? res.message : '删除成功');
      studentList();
    } else {
      ElMessage.error(res.message ? res.message : '很可惜，删除失败了');
    }
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

studentList();
</script>

<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
</style>